package com.github.alenfive.rocketapi.extendcommon.security.filter;

import com.alibaba.fastjson.JSON;
import com.github.alenfive.rocketapi.extendcommon.common.constant.HttpStatus;
import com.github.alenfive.rocketapi.extendcommon.common.utils.SecurityUtils;
import com.github.alenfive.rocketapi.extendcommon.common.utils.ServletUtils;
import com.github.alenfive.rocketapi.extendcommon.common.utils.StringUtils;
import com.github.alenfive.rocketapi.extendcommon.core.domain.AjaxResult;
import com.github.alenfive.rocketapi.extendcommon.core.domain.model.LoginUser;
import com.github.alenfive.rocketapi.extendcommon.core.redis.RedisCache;
import com.github.alenfive.rocketapi.extendcommon.error.BusinessErrorEnum;
import com.github.alenfive.rocketapi.extendcommon.service.TokenService;
import com.github.alenfive.rocketapi.extendcommon.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;

import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        System.out.println("进入请求");
        //获取token
        //判定token 格式是否正确
        //获取token信息
        //获取token 权限进行比对
        //先进行判断是否
        String authorization = request.getHeader("Authorization");

        LoginUser loginUser = tokenService.getLoginUser(request,response);

        if (StringUtils.isNotNull(loginUser)&& StringUtils.isNull(SecurityUtils.getAuthentication())) {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
